package cn.smartopen.aispace.controller.login;

import java.security.SignatureException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.smartopen.aispace.config.Config;
import cn.smartopen.aispace.service.user.UserService;
import cn.smartopen.aispace.status.ResponseCode;
import cn.smartopen.aispace.status.ResponseResult;
import cn.smartopen.aispace.utils.SignatureVerifier;
import cn.smartopen.aispace.utils.Utils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Tag(name = "用户登录" ,description = "用户使用第三方提供的网站登录系统")
@RestController
public class UserLoginController {


    @Autowired
    UserService userService;

    @Operation(summary = "获取令牌", description = "用户获取登录令牌字符串")
    @GetMapping("/user/token")
    public ResponseResult<String> getRandomStr(HttpSession session) {
        String randomStr = Utils.generateRandomString(Config.TOKEN_STR_LENGTH);
        session.setAttribute("tokenStr", randomStr);
        return new ResponseResult<>(ResponseCode.SUCCESS, randomStr);
    }

    @Operation(summary = "验证令牌", description = "用户使用自己的私钥签名令牌验证")
    @PostMapping("/user/token")
    public ResponseResult<String> confirmToken(
            HttpSession session,
            @Parameter(description = "用户公钥") @RequestParam("publicKey") String publicKey,
            @Parameter(description = "用户签名信息") @RequestParam("signatureMessage") String signatureMessage) {
        String tokenStr = (String) session.getAttribute("tokenStr");

        boolean res = false;
        // 验证签名
        try {
            res = SignatureVerifier.validate(signatureMessage, tokenStr, publicKey);
        } catch (SignatureException e) {
            log.error(e.getMessage());
        }

        if (res) {
            // 添加令牌到数据库
            userService.createToken(tokenStr,publicKey);
            return new ResponseResult<>(ResponseCode.SUCCESS);
        } else {
            return new ResponseResult<>(ResponseCode.SIGNATURE_ERROR);
        }

    }



    
}
